package com.taocyb.framework.mail;

import java.util.Arrays;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

/**
 * 邮件服务类.
 */
public class MailService {

	private static Logger logger = LoggerFactory.getLogger(MailService.class);
	
	private static final String DEFAULT_CHARSET = "UTF-8";

	private JavaMailSender mailSender;

	/**
	 * 发送MIME格式的邮件.
	 */
	public void sendMime(Mail mail) {
		try {
			MimeMessage msg = mailSender.createMimeMessage();
			MimeMessageHelper helper = new MimeMessageHelper(msg, true, DEFAULT_CHARSET);
			
			helper.setFrom(mail.getFrom(), mail.getFromAlias());
			helper.setTo(mail.getTo());
			helper.setSubject(mail.getSubject());
			helper.setText(mail.getContent(), true);

			mailSender.send(msg);
			logger.info("HTML版邮件已发送至{}", Arrays.toString(mail.getTo()));
		} catch (MessagingException e) {
			logger.error("构造邮件失败", e);
		} catch (Exception e) {
			logger.error("发送邮件失败", e);
		}
	}

	public void setMailSender(JavaMailSender mailSender) {
		this.mailSender = mailSender;
	}
}
